<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加模板"
    width="500px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="right"
    >
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入模板名称" />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input v-model="form.author" placeholder="请输入作者" />
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input
          v-model="form.note"
          type="textarea"
          rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useTemplateStore } from '@/stores/template'

const props = defineProps({
  modelValue: Boolean,
  settings: Object
})

const emit = defineEmits(['update:modelValue', 'submit'])
const templateStore = useTemplateStore()

const dialogVisible = ref(props.modelValue)
const loading = ref(false)
const formRef = ref(null)

// 使用 store 中的默认值
const form = ref({ ...templateStore.defaultForm })

const rules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 更新作者信息到 store
    templateStore.updateAuthor(form.value.author)
    
    // 组合完整的模板数据
    const templateData = {
      ...form.value,
      settings: props.settings
    }
    
    emit('submit', templateData)
  } catch (error) {
    ElMessage({
      ...templateStore.messageConfig,
      type: 'error',
      message: '请填写完整信息'
    })
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
}

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    // 打开对话框时，使用 store 中的默认值
    form.value = { ...templateStore.defaultForm }
  }
})

// 监听对话框内部状态变化
watch(() => dialogVisible.value, (val) => {
  emit('update:modelValue', val)
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 